import { SchemaNode } from '@coolphk/shared-types/low-code'

export interface SchemaProperty {
  type: string;
  title?: string;
  defaultValue?: unknown;
  properties?: Record<string, SchemaProperty>;
  items?: SchemaProperty;

  [key: string]: any;
}

export interface RootSchemaType {
  root: {
    type: string;
    title?: string;
    required?: string[];
    properties: Record<string, SchemaProperty>;
    [key: string]: any;
  };
}


export function useJsonSchemaToTree(serviceVersionVO: any, modelType: string) {
  // 根据modelType选择对应的模型和目标树
  const schema = modelType === 'inputModel'
    ? serviceVersionVO.inputModel?.schema as unknown as RootSchemaType
    : serviceVersionVO.outputModel?.schema as unknown as RootSchemaType

  const target = modelType === 'inputModel'
    ? serviceVersionVO.inputModelTree
    : serviceVersionVO.outputModelTree

  // 如果schema不存在或者target已经有内容，则直接返回
  if (!schema || !schema.root || !schema.root.properties || target.length != 0) {
    return
  }

  // 获取服务ID作为路径前缀
  const serviceId = serviceVersionVO.service.id

  const processProperty = (
    key: string,
    prop: SchemaProperty,
    parentPath: string = '',
    index: number = 0,
  ): SchemaNode => {
    // 构建当前节点的路径，适用于lodash的get方法
    // 当parentPath为空时，表示是根节点的直接子节点，应该使用[0].children[index]格式
    // 添加服务ID作为路径前缀
    const currentPath = parentPath
      ? `${serviceId}.${parentPath}.children[${index}]`
      : `${serviceId}.[0].children[${index}]`

    const node: SchemaNode = {
      label: prop.title,
      key: key,  // 直接使用当前层级的key
      type: prop.type,
      modelValue: prop.defaultValue,
      path: currentPath, // 添加path属性，可用于lodash的get方法
      component: [],
    }

    // 处理嵌套结构
    if (prop.type === 'object' && prop.properties) {
      node.children = Object.entries(prop.properties).map(([childKey, childProp], childIndex) =>
        processProperty(childKey, childProp, currentPath, childIndex),
      )
    } else if (prop.type === 'array' && prop.items) {
      // 处理数组项结构（保持items层级的key）
      if (prop.items.type === 'object' && prop.items.properties) {
        // 对于数组类型的对象，确保子项的路径格式正确
        node.children = Object.entries(prop.items.properties).map(([childKey, childProp], childIndex) =>
          processProperty(childKey, childProp, `${currentPath}.children[${childIndex}]`, childIndex),
        )
      } else {
        node.children = []
      }
    } else {
      node.children = []
    }

    return node
  }

  target.push({
    label: schema.root.title,
    key: 'root',
    type: schema.root.type,
    path: `${serviceId}.[0]`, // 根节点的path为数组索引格式，添加服务ID前缀
    children: Object.entries(schema.root.properties).map(([key, prop], index) =>
      processProperty(key, prop, '', index),
    ),
  })
}
